#include <brpc/channel.h>

#include <iostream>
#include <memory>
#include <string>
#include <thread>

#include "main.pb.h"

void callBack(brpc::Controller* controller, example::EchoResponse* resp) {
    std::shared_ptr<brpc::Controller> controller_ptr(controller);
    std::shared_ptr<example::EchoResponse> resp_ptr(resp);

    if (controller_ptr->Failed()) {
        std::cout << "rpc调用失败" << std::endl;
        return;
    }
    std::cout << "收到响应: " << resp_ptr->message() << std::endl;
}

int main() {
    // 1. 构造 channel 信道，连接服务器
    brpc::ChannelOptions channel_opts;
    channel_opts.connect_timeout_ms = -1;  // 链接等待超时时间
    channel_opts.timeout_ms = -1;          // 请求等待超时时间
    channel_opts.max_retry = 3;            // 请求重试次数
    channel_opts.protocol = "baidu_std";   // 序列化协议
    brpc::Channel channel;
    int ret = channel.Init("127.0.0.1:8080", &channel_opts);
    if (-1 == ret) {
        std::cout << "连接失败" << std::endl;
        return -1;
    }

    // 2. 构造 EchoService_stub 对象，用于进行 rpc 调用
    example::EchoService_Stub stub(&channel);

    // 3. 发起 rpc 调用
    example::EchoRequest req;
    example::EchoResponse* resp = new example::EchoResponse;
    req.set_message("hello world!!");

    brpc::Controller* controller = new brpc::Controller;
    auto closure = google::protobuf::NewCallback(callBack, controller, resp);   //异步
    stub.Echo(controller, &req, resp, closure);  // 异步调用

    // stub.Echo(controller, &req, resp, nullptr);  // 同步调用
    // if (controller->Failed()) { //同步
    //     std::cout << "rpc调用失败" << std::endl; //同步
    //     return -1; //同步
    // }

    std::this_thread::sleep_for(std::chrono::seconds(3));

    // std::cout << "收到响应: " << resp->message() << std::endl;   //同步
    // delete controller; //同步
    // delete resp; //同步

    return 0;
}